package com.sun.cart.service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.sun.commons.pojo.TbItemVO;
import com.sun.commons.pojo.UserByToken;
import com.sun.commons.utils.CookieUtils;
import com.sun.commons.utils.HttpClientUtil;
import com.sun.commons.utils.JsonUtils;
import com.sun.commons.utils.Tools;
import com.sun.dubbo.webmanage.service.TbItemDubboService;
import com.sun.redis.dao.RedisDao;
import com.sun.webmanage.model.TbItem;
import com.sun.webmanage.model.TbUser;

@Service("TbCatService")
public class TbCatServiceImpl implements TbCatService {

	@Value("${cart.cache.item}")
	private String itemCartKey;
	@Value("${passport.usertoken.href}")
	private String passport_usertoken_href;
	@Reference
	private TbItemDubboService tbItemDubboService;
	@Resource
	private RedisDao redisDao;

	@Value("TT_TOKEN")
	private String cookie_token;

	/**
	 * 获取用户信息 cookie-->redis-->userinfo
	 * 
	 * @param request
	 * @return
	 */
	private TbUser getTbUserInfo(HttpServletRequest request) {
		String token = CookieUtils.getCookieValue(request, cookie_token);
		String userJson = HttpClientUtil.doPost(passport_usertoken_href + token);
		UserByToken userToken = JsonUtils.jsonToPojo(userJson, UserByToken.class);
		TbUser tbUser = userToken.getData();
		return tbUser;
	}

	@Override
	public boolean addTbItemInCart(Long item_id, int num, HttpServletRequest request) {
		TbUser tbUser = getTbUserInfo(request);
		TbItem tbItem = tbItemDubboService.selectTbItemByPK(item_id);

		TbItemVO tbItemVO = new TbItemVO();
		String imageStr = tbItem.getImage();
		try {
			BeanUtils.copyProperties(tbItemVO, tbItem, true);
			tbItemVO.setImages(tbItem.getImages() == null || imageStr.equals("") ? new String[1] : imageStr.split(","));
			tbItemVO.setNum(num);
		} catch (Exception e) {
			e.printStackTrace();
		}

		List<TbItemVO> catList = null;

		if (redisDao.exists(itemCartKey + tbUser.getId())) {
			// 用户拥有购物车信息
			String cartJson = redisDao.getKey(itemCartKey + tbUser.getId());
			catList = JsonUtils.jsonToList(cartJson, TbItemVO.class);
			for (TbItemVO cartItem : catList) {
				if (cartItem.getId().equals(item_id)) {
					cartItem.setNum(cartItem.getNum() + num);
					// 如果购物车内有该商品，商品数量增加num
					redisDao.setKey(itemCartKey + tbUser.getId(), JsonUtils.objectToJson(catList));
					return true;
				}
			}
			// 如果购物车没有该商品，将商品信息加入购物车
			catList.add(tbItemVO);
			redisDao.setKey(itemCartKey + tbUser.getId(), JsonUtils.objectToJson(catList));
			return true;
		}

		catList = new ArrayList<>();
		catList.add(tbItemVO);
		redisDao.setKey(itemCartKey + tbUser.getId(), JsonUtils.objectToJson(catList));
		return true;

	}

	@Override
	public List<TbItemVO> listCartTbitem(HttpServletRequest request) {
		TbUser tbUser = getTbUserInfo(request);
		String cartJson = redisDao.getKey(itemCartKey + tbUser.getId());
		List<TbItemVO> retList = null;
		if(cartJson!=null && !cartJson.equals("")){
			retList = JsonUtils.jsonToList(cartJson, TbItemVO.class);
		}else{
			retList = new ArrayList<>(1);
		}
		for (TbItemVO tbItemVO : retList) {
			String image = tbItemVO.getImage();
			String[] image_array = image==null?new String[1]:image.split(",");
			tbItemVO.setImages(image_array);
		}
		return retList;
	}

	@Override
	public boolean updateTbItemCart(Long item_id, int num, HttpServletRequest request) {
		TbUser tbUser = getTbUserInfo(request);
		String cartJson = redisDao.getKey(itemCartKey + tbUser.getId());
		List<TbItemVO> retList = JsonUtils.jsonToList(cartJson, TbItemVO.class);
		for (TbItemVO cartItem : retList) {
			if (cartItem.getId().equals(item_id)) {
				cartItem.setNum(num);// 更新数量，为零时不会清空
			}
		}
		redisDao.setKey(itemCartKey + tbUser.getId(), JsonUtils.objectToJson(retList));
		return true;
	}

	@Override
	public boolean deleteTbItemCart(String item_ids, HttpServletRequest request) {
		TbUser tbUser = getTbUserInfo(request);
		String cartJson = redisDao.getKey(itemCartKey + tbUser.getId());
		List<TbItemVO> retList = JsonUtils.jsonToList(cartJson, TbItemVO.class);
		String[] item_id_array = item_ids.split(",");
		Iterator<TbItemVO> iter = retList.iterator();
		while (iter.hasNext()) {
			TbItemVO element = iter.next();
			if (Tools.indexOf(item_id_array, element.getId().toString())) {
				iter.remove();
			}
		}
		redisDao.setKey(itemCartKey + tbUser.getId(), JsonUtils.objectToJson(retList));
		return true;
	}


}
